/*
 * @Author: 一路向阳 tt_sunzhenfeng@163.com
 * @Date: 2024-05-24 09:12:50
 * @LastEditors: 一路向阳 tt_sunzhenfeng@163.com
 * @LastEditTime: 2024-05-24 10:12:51
 * @FilePath: \vue3_nuxt_demo\server\api\note\index.delete.ts
 * @Description: 删除文章接口
 */
import Joi from 'joi';
import { responseJson, getLoginUid } from '@/server/utils/helper';
import { getDB } from '@/server/utils/db';

/**
 * 1、判断用户是否登录
 * 2、已登录则删除文章
 */

export default defineEventHandler(
  async (event) => {
    //判断用户登录
    const uid = getLoginUid(event);

    // 判断用户id
    if (uid === 0) {
      setResponseStatus(event, 401);
      return responseJson(401,{
        success: false,
        msg: '请先登录'
      });
    }

    // 获取请求体
    const body = await readBody(event);
    // 数据校验
    const schema = Joi.object({
      noteId: Joi.number().required()
    });

    // 校验请求体
    try {
      const value = await schema.validateAsync(body);
    }
    catch (error) {
      return responseJson(400,  {
        success: false,
        msg: '参数错误',
        error: error
      });
    }

    // 数据库交互
    const { find, close } = getDB();

    // 查询
    const con = find();
    
    try {
      // 请求体
      const { noteId } = body;
      //删除文章
      const [rows] = await con.execute(
        'DELETE FROM `notes` WHERE `id`=? AND `uid`=?',
        [noteId, uid]
      );

      if (rows.affectedRows === 0){
        return  responseJson(400,{
          success: false,
          msg: '删除失败'
        });
      }

      return  responseJson(200,{
        success: true,
        msg: '删除成功'
      });
    }
    catch (error){

      setResponseStatus(event,500);

      return responseJson(500,{
        success: false,
        msg: '服务器错误',
        error: error
      });
    }
    finally {
      // 释放连接
      close();
    }

  }
);